//
//  AmendPhoneViewController.m
//  ChineseCollegeStudentsNetwork
//
//  Created by 刘喆 on 2018/5/14.
//  Copyright © 2018年 刘喆. All rights reserved.
//

#import "AmendPhoneViewController.h"
#import "CEAccessoryTextField.h"

@interface AmendPhoneViewController ()<UITextFieldDelegate>

/** 解绑手机号 */
@property(nonatomic, strong) CEAccessoryTextField *phoneTextField;

@end

@implementation AmendPhoneViewController

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"修改手机号";
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupConstraints];
    
    UIBarButtonItem *saveItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveAction)];
    self.navigationItem.rightBarButtonItem = saveItem;

}

- (void)saveAction {
    
    if (self.phoneTextField.text.length == 0) {
        ShowMessage(@"请输入新的手机号码");
        return;
    }
    
    [MLAHttpManage postHttpType:MLAHttpRequestType_Put hostType:MLAHttpHostType_Api api:[self getUserIdApi:@"/api/v1/users"] params:@{@"mobile":self.phoneTextField.text}.mj_JSONString success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        [UserManager sharedInstance].userModel.value.mobile = self.phoneTextField.text;
        ShowMessage(@"修改成功");
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^{
        ShowMessage(@"修改失败,请重新修改");
    }];
}

#pragma mark - Constraints

- (void)setupConstraints {
    
    [self.phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(50);
        make.centerX.equalTo(self.view);
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(0);
        make.height.mas_equalTo(@50);
    }];
    
}

- (CEAccessoryTextField *)phoneTextField {
    
    if (!_phoneTextField) {
        _phoneTextField = [[CEAccessoryTextField alloc] init];
        _phoneTextField.type = CEAccessoryTextFieldTypeLabel;
        _phoneTextField.titleLabel.text = @"手机号：";
        _phoneTextField.placeholder = [UserManager sharedInstance].userModel.value.mobile;
        _phoneTextField.delegate = self;
        _phoneTextField.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_phoneTextField];
    }
    return _phoneTextField;
    
    
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    
    return YES;
}

#pragma mark - UIControl

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self resignAllTextFieldResponder];
}

#pragma mark - Private

- (void)resignAllTextFieldResponder {
    
    [self.phoneTextField resignFirstResponder];
    
}


@end
